<?php
/**
 * Created by PhpStorm.
 * User: 刘红波 <liuhb@cqjcdflzxsws.com>
 * Date: 2018/11/20
 * Time: 14:15
 */

namespace app\api\until;

use Elasticsearch\ClientBuilder;
use Elasticsearch\Common\Exceptions\Curl\CouldNotConnectToHost;

class ESearch extends ClientBuilder
{
    private $client;

    private $host = [
        '127.0.0.1:9200'
    ];

    public $data = [];

    /**
     * ESearch constructor.
     */
    public function __construct()
    {
        try {
            $this->client = ClientBuilder::create()->setHosts($this->host)
                ->setRetries(5)->build();
        } catch (CouldNotConnectToHost $exception) {
            return [
                'code' => $exception->getCode(),
                'line' => $exception->getLine(),
                'msg' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'previous' => $exception->getPrevious(),
                'trace' => $exception->getTrace(),
                'trace_str' => $exception->getTraceAsString(),
            ];
        }
    }


    public function setParams($index, $type = null, $body = null)
    {
        if (!$index) {
            var_dump('index不能为空');
            exit;
        }
        $temp['index'] = $index;
        if ($type) {
            $temp['type'] = $type;
        }
        if ($body) {
            $temp['body'] = $body;
        }
        $this->data = $temp;
        unset($temp);
        return $this;
    }

    public function addParams($data)
    {
        $temp = array_merge($this->data, $data);
        $this->data = $temp;
        return $this;
    }

    public function getClient()
    {
        return $this->client;
    }
}